package com.ruoyi.attendance.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ruoyi.attendance.config.BaiduApiConfig;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Base64;

@Component
public class BaiduFaceMatchUtil {
    private static final String ACCESS_TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token";
    private static final String FACE_MATCH_URL = "https://aip.baidubce.com/rest/2.0/face/v3/match";

    @Autowired
    private BaiduApiConfig baiduApiConfig;

    private final ObjectMapper objectMapper = new ObjectMapper();
    private final OkHttpClient client = new OkHttpClient();

    /**
     * 获取访问令牌
     * @return 访问令牌
     */
    public String getAccessToken() {
        FormBody formBody = new FormBody.Builder()
                .add("grant_type", "client_credentials")
                .add("client_id", baiduApiConfig.getApiKey())
                .add("client_secret", baiduApiConfig.getSecretKey())
                .build();

        Request request = new Request.Builder()
                .url(ACCESS_TOKEN_URL)
                .post(formBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            String responseBody = response.body().string();
            return objectMapper.readTree(responseBody).get("access_token").asText();
        } catch (Exception e) {
            throw new RuntimeException("获取访问令牌失败", e);
        }
    }

    /**
     * 人脸对比
     * @param livePhoto 实时人脸照片的 Base64 编码
     * @param originalPhoto 原照片的 Base64 编码
     * @return 对比结果
     */
    public String faceMatch(String originalPhoto, String livePhoto) {
        ArrayNode images = objectMapper.createArrayNode();

        ObjectNode originalImage = objectMapper.createObjectNode();
        originalImage.put("image", originalPhoto);
        originalImage.put("image_type", "BASE64");
        originalImage.put("face_type", "LIVE");
        originalImage.put("quality_control", "LOW");
        originalImage.put("liveness_control", "NONE");
        images.add(originalImage);

        ObjectNode liveImage = objectMapper.createObjectNode();
        liveImage.put("image", livePhoto);
        liveImage.put("image_type", "BASE64");
        liveImage.put("face_type", "LIVE");
        liveImage.put("quality_control", "LOW");
        liveImage.put("liveness_control", "NORMAL");
        images.add(liveImage);

        try {
            String jsonPayload = objectMapper.writeValueAsString(images);
            MediaType JSON = MediaType.get("application/json; charset=utf-8");
            // 使用新的方式创建 RequestBody
            RequestBody body = RequestBody.create(JSON, jsonPayload.getBytes());

            String url = FACE_MATCH_URL + "?access_token=" + getAccessToken();
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();

            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }
                return response.body().string();
            }
        } catch (IOException e) {
            throw new RuntimeException("构建或处理 JSON 数据时出错", e);
        }
    }

    /**
     * 将二进制图片数据转换为 Base64 编码
     * @param imageBytes 二进制图片数据
     * @return Base64 编码字符串
     */
    public String imageToBase64(byte[] imageBytes) {
        return Base64.getEncoder().encodeToString(imageBytes);
    }
}